package com.jh.paymentchannel.service;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.jh.paymentchannel.pojo.SwiftBrandMerchant;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jh.paymentchannel.business.BrandManageBusiness;
import com.jh.paymentchannel.util.SignUtils;
import com.jh.paymentchannel.util.XmlUtils;


@Controller
public class SwiftOrderQueryService {


    private static final Logger log = LoggerFactory.getLogger(SwiftOrderQueryService.class);

    @Autowired
    private BrandManageBusiness brandManageBusiness;

    /**
     * 发起请求 请求url, 并返回跳装的url
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/swift/order/query")
    public @ResponseBody
    Object getOrder(HttpServletRequest request,
                    @RequestParam(value = "mch_id") String mchId,
                    @RequestParam(value = "bill_date") String billdate
    ) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost postMethod = new HttpPost("https://download.swiftpass.cn/gateway");
        SwiftBrandMerchant brandMerchant = brandManageBusiness.getSwiftBrandMerchantByMchId(mchId);
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("service", "pay.bill.merchant"));
        nvps.add(new BasicNameValuePair("mch_id", mchId));
        nvps.add(new BasicNameValuePair("bill_type", "ALL"));
        nvps.add(new BasicNameValuePair("bill_date", billdate));
        String nonce_str = String.valueOf(new Date().getTime());
        nvps.add(new BasicNameValuePair("nonce_str", nonce_str));
        String sign = "";
        String res;
        try {
            sign = SignUtils.signMD5Data(nvps, brandMerchant.getSubMerchantKey());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        SortedMap<String, String> paramsmap = new TreeMap<String, String>();

        paramsmap.put("service", "pay.bill.merchant");
        paramsmap.put("mch_id", mchId);
        nvps.add(new BasicNameValuePair("bill_type", "ALL"));
        nvps.add(new BasicNameValuePair("bill_date", billdate));
        paramsmap.put("nonce_str", nonce_str);
        paramsmap.put("sign", sign);

        StringEntity entityParams = new StringEntity(XmlUtils.parseXML(paramsmap), "utf-8");


        postMethod.setEntity(entityParams);
        CloseableHttpResponse response;
        try {
            response = httpClient.execute(postMethod);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }

        if (response != null && response.getEntity() != null) {
            Map<String, String> resultMap = null;
            try {
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "UTF-8");
            } catch (Exception ignored) {

            }
            res = XmlUtils.toXml(resultMap);
        } else {
            res = "操作失败";
            //map.put("resp_code", "failed");
        }


        return null;
    }

}
